﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Mvc;
using AzureUtilities;
using MonkeysWithTypeWriters.ServiceContracts;

namespace MonkeysWithTypewriters.Web.Controllers
{
    /// <summary>
    /// default controller for the project
    /// </summary>
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Services a request to create a novel 
        /// </summary>
        /// <param name="novelSubmission"></param>
        /// <returns></returns>
        public ActionResult CreateNovel(NovelSubmission novelSubmission)
        {
            //get an endpoint through the load balancer
            var endpoint = RoleLoadBalancer.GetEndpointForRole("MonkeysWithTypewriters.WebService", "InternalEndpoint");
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri(string.Format("http://{0}/api/", endpoint.IPEndpoint))
            };

            //send a request to create a novel 
            NovelResult result = null;

            var fetchTask = httpClient.PostAsJsonAsync("MonkeyText", novelSubmission)
                .ContinueWith(requestTask =>
            {
                HttpResponseMessage response = requestTask.Result;
                response.EnsureSuccessStatusCode();
                result = response.Content.ReadAsAsync<NovelResult>().Result;
            });

            //wait for the task to complete before continuing with the method
            fetchTask.Wait();

            return View(result);
        }

    }
}
